package com.geor.gcr.idc;

import com.geor.common.msg.Encoder;
import com.geor.common.msg.Encoder64Default;
import com.geor.common.msg.Strings;
import com.geor.gcf.sfp.protocol.FileMeta;
import com.geor.gcf.sfp.protocol.SfpResponse;
import com.geor.gcr.sfz.client.ResourceSender;
import com.geor.scan.interfaces.Recognizer;

import org.nutz.json.Json;
import org.nutz.lang.Files;

import java.io.File;
import java.io.FileInputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 */
public class RecognizerImpl implements Recognizer {
    static Encoder encoder = new Encoder64Default();

    private String cmd;

    public RecognizerImpl(String cmd) {
        this.cmd = cmd;
    }

    @Override
    public Map<String, String> execute(File file) {
        try {
            ResourceSender sender = new ResourceSender();
            sender.setHost(Constants.address, Constants.port);
            FileInputStream fis = new FileInputStream(file);
            SfpResponse response = sender.putFile(cmd, fis);;
            if (!"0000".equals(response.getResult().getCode())) {
                throw new Exception(response.getResult().getDesc());
            }

            List<FileMeta> fileMetas = response.getContents().getFileMetas();
            for (FileMeta fileMeta : fileMetas) {
                if (!Strings.isEmpty(fileMeta.getDesc())) {
                    System.out.println(String.format("failed: %s, error: %s", fileMeta.getName(), encoder.decode(fileMeta.getDesc())));
                }

                String crResult = fileMeta.getData();
                if (Strings.isEmpty(crResult)) {
                    System.out.println("failed:" + fileMeta.getName());
                    continue;
                }
                String result = encoder.decode(crResult);

                Map<String,String> map = Json.fromJsonAsMap(String.class, result);

                return map;
            }
        } catch (Exception e) {
            e.printStackTrace();
            Files.deleteFile(file);
        }

        Map<String,String> map = new HashMap<>();
        map.put("RETCODE", "9999");
        return map;
    }
}
